package com.yh.javabean;



import com.yh.javabean.AppConfig;
import com.yh.javabean.user;
import com.yh.javabean.UserMapper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.Statement;
import java.util.List;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = AppConfig.class)
public class AppConfigTest {

    private UserMapper userMapper;
    private DataSource dataSource;

    @Before
    public void setUp() throws Exception {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        userMapper = context.getBean(UserMapper.class);
        dataSource = context.getBean(DataSource.class);

        // Initialize database
        try (Connection conn = DataSourceUtils.getConnection(dataSource);
             Statement stmt = conn.createStatement()) {
            stmt.execute("CREATE TABLE IF NOT EXISTS user (id INT PRIMARY KEY, name VARCHAR(100))");
            stmt.execute("INSERT INTO user (id, name) VALUES (1, 'John Doe')");
        }
    }

    @Test
    public void testFindAll() {
        List<user.User> users = userMapper.findAll();
        for (com.yh.javabean.user.User user : users) {
            System.out.println(user.getName());
        }
    }
}
